﻿using System;
using System.Web;
using StructureMap;
using TimeTracker.Core.Domain.Entities;

namespace TimeTracker.Core.Services.Implementation
{
    [Pluggable("Default")]
    public class WebContext : IWebContext
    {
        public int KorisnikId
        {
            get
            {
                return !string.IsNullOrEmpty(GetQueryStringValue("KorisnikId")) ? Convert.ToInt32(GetQueryStringValue("KorisnikId")) : 0;
            }
        }

        public bool Prijavljen
        {
            get
            {
                if(ContainsInSession("Prijavljen"))
                {
                    return (bool)GetFromSession("Prijavljen");
                }
                return false;
            }
            set
            {
                SetInSession("Prijavljen", value);
            }
        }

        public string KorisnickoIme
        {
            get
            {
                return ContainsInSession("KorisnickoIme") ? GetFromSession("TrenutniKorisnik").ToString() : "";
            }
            set
            {
                SetInSession("TrenutniKorisnik", value);
            }
        }

        public Korisnik TrenutniKorisnik
        {
            get 
            { 
                if(ContainsInSession("TrenutniKorisnik"))
                {
                    return GetFromSession("TrenutniKorisnik") as Korisnik;
                }
                return null;
            }
            set
            {
                SetInSession("TrenutniKorisnik", value);
            }
        }

        public void ClearSession()
        {
            HttpContext.Current.Session.Clear();
        }

        public bool ContainsInSession(string key)
        {
            return HttpContext.Current.Session != null && HttpContext.Current.Session[key] != null;
        }

        public void RemoveFromSession(string key)
        {
            HttpContext.Current.Session.Remove(key);
        }

        private string GetQueryStringValue(string key)
        {
            return HttpContext.Current.Request.QueryString.Get(key);
        }

        private void SetInSession(string key, object value)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return;
            }
            HttpContext.Current.Session[key] = value;
        }

        private object GetFromSession(string key)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return null;
            }
            return HttpContext.Current.Session[key];
        }

        private void UpdateInSession(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }
    }
}
